import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/json/user_item.dart';

import '../json/food_item.dart';

//code 2开头都是请求成功的，只不过业务上可能不成功
//code 4开头都是请求不成功的。（一般都是 客户端-前端代码问题）
class FoodApi {
  late Dio _dio;
  String baseUrl = "http://192.168.1.12:8080/FoodController";
  String contents = "";

  FoodApi() {
    _dio = Dio();
    // 设置contentType
    // _dio.options.headers['Content-Type'] = 'application/x-www-form-unlencoded';
  }

  // var response = null;
  //注意，在界面调用接口前， 都先检测一下apikey的值。
  Future<ResponseItem<List<FoodItem>?>> listFoodByBusinessId(String businessId) async {
    var url =  baseUrl+"/listFoodByBusinessId/${businessId}";

    try {
      Response response = await _dio.get(url);
//如果没有该businessId类型，或者该类型没有商家，就会返回[]
//       print(response.data);
      if(response.data.length==0){
        return ResponseItem(code: 201, data: null, message: "没有该businessId，或者该商家没有商品");
      }else{
        List rd = response.data;
        List<FoodItem> foodItemList = rd.map((e) => FoodItem.fromJson(e)).toList();
        return ResponseItem<List<FoodItem>>(code: 200, data: foodItemList, message: "查找成功");
      }
    } catch (e) {
      print('******listFoodByBusinessId-Error: $e');
      return ResponseItem(code: 400, data: null, message: "客户端代码有问题，$e");
        // if(response.data.length==0){
        //   print('******listFoodByBusinessId-Error: $e');
        //   return ResponseItem(code: 400, data: null, message: "客户端代码有问题，$e");
        // }else{
        //   print('******listFoodByBusinessId-Error: $e');
        //   List rd = response.data;
        //   List<FoodItem> foodItemList = rd.map((e) => FoodItem.fromJson(e)).toList();
        //   return ResponseItem<List<FoodItem>>(code: 202, data: foodItemList, message: "查找成功，但是系统发现错误：$e");
        // }
    }
  }

}

void main()async{
  FoodApi foodApi = FoodApi();
  // var res = await userApi.userRegister("11111178912", "12345678912", "小李", 1);
  var res = await foodApi.listFoodByBusinessId("10001");
  print("${res.code}:${res.message}");
  // print("${res.code}:${res.message}\n查找结果：${res.data}");
}
